package com.okhttp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttpUtil {

	@SuppressWarnings("deprecation")
	public final static OkHttpClient client = new OkHttpClient.Builder()
			.sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
			.hostnameVerifier(SSLSocketClient.getHostnameVerifier()).build();;

	private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	private static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

	public interface ContentListener {
		void success(String content);

		void failed(int code, String err);
	}

	public interface PercentListener {
		void process(int percent);
	}

	public static String get(String url) {
		return get(getRequest(url));
	}

	public static void getAsyn(String url, Callback callback) {
		Request request = getRequest(url);
		client.newCall(request).enqueue(callback);
	}

	public static String get(Request request) {
		Response response = null;
		try {
			response = baseGet(request).execute();
			if (response.isSuccessful())
				return response.body().string();
			else {
				System.err.println(response.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				response.close();
		}
		return null;
	}

	public static void get(String url, ContentListener listener) {
		get(getRequest(url), listener);
	}

	public static void get(Request request, ContentListener listener) {
		Response response = null;
		try {
			response = baseGet(request).execute();
			if (response.isSuccessful()) {
				listener.success(response.body().string());
			} else {
				String msg = response.toString();
				listener.failed(response.code(), msg);
			}
		} catch (IOException e) {
			e.printStackTrace();
			listener.failed(-1, "CONNECT_ERROR," + e.toString());
		}
	}

	/**
	 * 获取图像字节数组
	 *
	 * @param imageUrl
	 * @return
	 */
	public static byte[] getImage(String imageUrl) {
		Response response = null;
		try {
			response = baseGet(getRequest(imageUrl)).execute();
			if (response.isSuccessful()) {
				return response.body().bytes();
			} else {
				return new byte[0];
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new byte[0];
	}

	public static String post(String url, String json) {
		Response response = null;
		try {
			response = basePost(url, json).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				System.err.println(response.toString());
			}
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				response.close();
		}
		return null;
	}

	public static boolean download(String url, String filePath, PercentListener listener) {
		return download(getRequest(url), filePath, listener);
	}

	/**
	 * 下载文件
	 * 
	 * @param request
	 * @param filePath
	 * @param listener
	 * @return
	 * @date 2020/03/08 14:18:09
	 * @author zincredible
	 */
	public static boolean download(Request request, String filePath, PercentListener listener) {
		byte[] buf = new byte[1024];

		InputStream is = null;
		FileOutputStream fos = null;
		try {
			File file = new File(filePath);
			File dir = file.getParentFile();
			if (!dir.isDirectory()) {
				dir.mkdirs();
			}
			Response response = client.newCall(request).execute();
			is = response.body().byteStream();
			long total = response.body().contentLength();
			fos = new FileOutputStream(file);
			long sum = 0;
			int progress = 0;
			int len = 0;
			while ((len = is.read(buf)) != -1) {
				fos.write(buf, 0, len);
				sum += len;
				progress = (int) (sum * 1.0f / total * 100);
				// 更新进度
				if (listener != null)
					listener.process(progress);
			}
			fos.flush();
			if (progress != 100 && listener != null) {
				listener.process(100);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static Request getRequest(String url) {
		Request request = new Request.Builder().url(url).build();
		return request;
	}

	public static Request getHeaderRequest(String url, Map<String, String> headMap) {
		Request.Builder builder = new Request.Builder().url(url);
		if (headMap != null) {
			Set<String> keySet = headMap.keySet();
			for (String key : keySet)
				builder.addHeader(key, headMap.get(key));
		}
		return builder.build();
	}

	public static Call baseGet(Request request) {
		return client.newCall(request);
	}

	public static Call basePost(String url, String json) {
		Request.Builder builder = new Request.Builder().url(url);
		if (json != null && !"".equals(json)) {
			RequestBody body = RequestBody.create(JSON, json);
			builder.post(body);
		} else {
			builder.post(RequestBody.create(FORM, ""));
		}
		Request request = builder.build();
		return client.newCall(request);
	}

}
